<?php
namespace App\Admin\Socialite;

use GuzzleHttp\RequestOptions;
use Laravel\Socialite\Two\User;
use Laravel\Socialite\Two\AbstractProvider;
use Illuminate\Support\Arr;


class AuthingProvider extends AbstractProvider
{
    // 默认scopes
    protected $scopes = ['openid', 'profile'];

    // 请求范围的分隔字符，默认逗号
    protected $scopeSeparator = ' ';

    // 关闭session储存state
    protected $stateless = true;

    // 指示是否应使用PKCE 为false时不使用session
    protected $usesPKCE = false;

    protected function getAuthUrl($state){
    	return $this->buildAuthUrlFromBase('https://ssssssssssssssssssrefre.authing.cn/oidc/auth', $state);
    }

    protected function getTokenUrl(){
        return 'https://ssssssssssssssssssrefre.authing.cn/oidc/token';
    }

    protected function getUserByToken($token){
        $userUrl = 'https://ssssssssssssssssssrefre.authing.cn/oidc/me';

        $response = $this->getHttpClient()->get($userUrl, [
            RequestOptions::HEADERS => [
                'Authorization' => 'Bearer '.$token,
            ],
        ]);

        $user = json_decode($response->getBody(), true);

        return $user;
    }

    /**
     *  subject 的缩写，唯一标识，一般为用户 ID
     */
    protected function mapUserToObject(array $user){
        return (new User)->setRaw($user)->map([
            'id'       => $user['sub'],
            'nickname' => Arr::get($user, 'nickname'),
            'name'     => Arr::get($user, 'name'),
            'email'    => Arr::get($user, 'email'),
            'avatar'   => Arr::get($user, 'picture'),
        ]);
    }
}